from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset, DatasetDict
import torch

# 1. 加载数据集
# 假设你有一个 JSON 文件，包含训练数据
data_files = {'train': './train.json', 'test': './test.json'}
dataset = load_dataset('json', data_files=data_files)

# 2. 预处理数据
tokenizer = BertTokenizer.from_pretrained('D:\\work\program\\pytorch_models\\bert-base-chinese')

def preprocess_function(examples):
    return tokenizer(examples['text'], truncation=True, padding=True, max_length=128)

encoded_dataset = dataset.map(preprocess_function, batched=True)

# 3. 定义模型
num_labels = len(set(dataset['train']['label']))  # 假设标签列名为 'label'
model = BertForSequenceClassification.from_pretrained('D:\\work\program\\pytorch_models\\bert-base-chinese', num_labels=num_labels)

# 4. 定义训练参数
training_args = TrainingArguments(
    output_dir='./results',
    evaluation_strategy='epoch',
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=3,
    weight_decay=0.01,
)

# 5. 定义 Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=encoded_dataset['train'],
    eval_dataset=encoded_dataset['test'],
)

# 6. 训练模型
trainer.train()

# 7. 评估模型
results = trainer.evaluate()
print(results)

# 保存模型和 tokenizer
model_save_path = 'D:/work/code/clark/gitee/py_llm/bert/train/eval'
model.save_pretrained(model_save_path)
tokenizer.save_pretrained(model_save_path)